package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.entity.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.minio.MinIOService;
import com.heima.common.util.MediaThreadLocal;
import com.heima.media.dto.WmMaterialDto;
import com.heima.media.entity.WmMaterial;
import com.heima.media.mapper.WmMaterialMapper;
import com.heima.media.service.IWmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-06-22
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements IWmMaterialService {

    @Autowired
    private MinIOService minIOService;
    @Override
    public ResponseResult<WmMaterial> upload(MultipartFile file) {
//        获取用户id
        Integer userId = MediaThreadLocal.get().getUserId();
        System.out.println(userId);
//        图片上传 , 获取url
        String url = minIOService.upload(file);
        System.out.println(url);


        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUrl(url);
        wmMaterial.setUserId(userId);
        wmMaterial.setType(0);
        wmMaterial.setIsCollection(false);
        wmMaterial.setCreatedTime(new Date());
        this.save(wmMaterial);

        return ResponseResult.okResult(wmMaterial);

    }

    @Override
    public ResponseResult listByPage(WmMaterialDto dto) {
//        判断用户是否存在
        User user = MediaThreadLocal.get();
        if ( user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
//        存在，判断是否收藏
        Wrapper<WmMaterial> query = new LambdaQueryWrapper<>();
        if (dto.getIsCollection() != null) {
         ((LambdaQueryWrapper<WmMaterial>) query).eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
//        查询用户
        ((LambdaQueryWrapper<WmMaterial>) query).eq(WmMaterial::getUserId,user.getUserId());
//        创建时间倒序
        ((LambdaQueryWrapper<WmMaterial>) query).orderByDesc(WmMaterial::getCreatedTime);
//        分页
        IPage<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());
        this.page(page, query);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
        return result;
    }
}
